/*
 * @Description:逻辑类 非模块元素相关入在这里统一处理
 * @Version: 2.0
 * @Autor: wiz
 * @Date: 2022-08-30 16:53:40
 * @LastEditors: swc shanwenchao12138@163.com
 * @LastEditTime: 2025-03-20 14:04:19
 */

import { N_oInteraction, N_oSetupPanel } from '@/types';
import { T_bgdAPI } from './class/api';
import { N_oBaseGrid, Tsrv, ifs, ts } from './config';

// 编辑类
export class T_editor extends T_bgdAPI {
  // 编译状态 'none|modify|new
  public editorStatus: 'none' | 'modify' | 'new' = 'none';

  private compName: string;

  private compBox: ifs.I_compBox;

  private compID: string;

  private contorlEvent: Map<string, Array<() => void>> = new Map();

  private fieldsSearchFilter: Map<string, Array<() => void>> = new Map();

  // 组件配合 在外部实例化
  private TCoordination: ifs.I_compCoordination;

  // 临时存储toolbar状态
  private toolbarStatusBak: any = null;

  // 本操作锁定持有的锁
  public editLockNum: Map<
    string,
    {
      funID: string;
      cmd: 'lock' | 'unLock';
      rowID: string;
      key: string;
    }
  > = new Map();

  // 任务执行器
  // private tasker: ts.T_task = new ts.T_task(1000);
  private tasker: ts.T_task;

  private taskerInfo: {
    eventName: string;
    intervalTime: number;
  } = null;

  constructor(self: any, compBoxInfo: ifs.I_compBoxInfo) {
    super(self);
    this.compName = self.G_compName;
    this.compBox = compBoxInfo.TcompBox;
    this.compID = compBoxInfo.compID;
    this.Teditor = this;
  }

  // 添加注册控件事件
  public regControlEventCallBack(actionName: string, p: () => void) {
    if (this.contorlEvent.has(actionName)) {
      const eArr = this.contorlEvent.get(actionName);
      eArr.push(p);
    } else {
      this.contorlEvent.set(actionName, [p]);
    }
  }

  // 调用控件注册的事件
  public callControlEvent(actionName: string) {
    if (this.contorlEvent.has(actionName)) {
      const eArr = this.contorlEvent.get(actionName);
      if (!Tsrv.utils.noValue(eArr) && Array.isArray(eArr)) {
        eArr.forEach(el => {
          el();
        });
      }
    }
  }

  public clearFiltersAndLoadData(): void {
    this.clearSort();
    this.clearFilter();
    if (!Tsrv.utils.noValue(this.oBaseGrid.config?.qbeSearch)) {
      if (this.oBaseGrid.config.qbeSearch.enable && this.oBaseGrid.qbeQuery)
        this.getCompItemByName('queryByExample').setFormData();
    }
    this.loadTableData().then(() => {
      this.oBaseGrid.$msg('50003,FE,0,');
    });
  }

  public doSave(changes: any): Promise<any> {
    return this.batchCTD(changes);
  }

  public doDelete(): Promise<any> {
    return this.delCTD();
  }

  /**
   * save 保存
   */
  public save() {
    // const actionCfg = this.actionsCfg;
    const oBaseGrid = this.oBaseGrid;
    oBaseGrid
      .validate()
      .then(() => {
        if (oBaseGrid.loading === false) {
          oBaseGrid.loading = true;
          const msg = oBaseGrid.$Message.loading({
            content: oBaseGrid.$srv.getI18nByPath('prompt.saving') as string,
            duration: 0
          });

          const changes = oBaseGrid.getChanges();

          this.doSave(changes)
            .then(resp => {
              oBaseGrid.loading = false;
              this.editorStatus = 'none';
              this.sendEventCoordination('save');
              this.unLockALL(); // 解锁
              if (resp) {
                this.seSavedCurrentRow(changes);
              }
              // @ts-ignore
              msg();
            })
            .catch(() => {
              oBaseGrid.loading = false;
              // @ts-ignore
              msg();
            });
        }
      })
      .catch(() => {
        oBaseGrid.$msg(
          oBaseGrid.$srv.getI18nByPath('warm.tableFormatIncorrect')
        );
      });
  }

  /**
   * 删除前
   */
  public beforeDelete() {
    const actionsCfg = this.actionsCfg;
    const oBaseGrid = this.oBaseGrid;
    if (this.oBaseGrid.loading === false) {
      oBaseGrid.loading = true;
      const msg = oBaseGrid.$Message.loading({
        content: oBaseGrid.$srv.getI18nByPath('prompt.deleting') as string,
        duration: 0
      });

      this.doDelete()
        .then(() => {
          oBaseGrid.loading = false;
          const grid = this.getGrid();
          // grid.clearCurrentRow();
          const removes = this.grid.getCheckboxRecords();
          const rowIndex = grid.getRowIndex(removes[removes.length - 1]) ?? 0;
          this.setCurrRowIdx(rowIndex);
          // @ts-ignore
          msg();
        })
        .catch(() => {
          oBaseGrid.loading = false;
          // @ts-ignore
          msg();
        });
    }
  }

  /**
   * @description: 保存后 调整当前行
   * @param changes
   */
  public seSavedCurrentRow(changes: any) {
    let ID: string = '';
    if (changes.updateRecords.length > 0) {
      const curData = changes.updateRecords[changes.updateRecords.length - 1];
      ID = curData.find(el => el.field === 'id')?.value;
    }
    if (changes.insertRecords.length > 0) {
      const curData = changes.insertRecords[changes.insertRecords.length - 1];
      ID = curData.find(el => el.field === 'id')?.value;
    }
    if (Tsrv.noValue(ID)) {
      return;
    }
    const grid = this.getGrid();
    const data = grid.getTableData().fullData;
    const currentRow = Tsrv.utils.find(data, el => el.id === ID);
    const rowIndex = grid.getRowIndex(currentRow) ?? 0;
    // grid.clearCurrentRow();
    this.setCurrRowIdx(rowIndex);
  }

  /**
   * @description: 打印
   * 原1.0打印选择的行改为全局打印，如果要选择打印则启用过滤
   * @return {*}
   * @author: wiz
   * @Date: 2022-12-26 20:36:46
   * @LastEditors: wiz
   * @LastEditTime: Do not edit
   */
  public print() {
    // const ids = this.grid.getCheckboxRecords().map(el => {
    //   return el.id;
    // });
    // if (ids.length > 0) {
    //   this.oBaseGrid.isOpenPrint = true;
    // }
    if (this.grid.getData().length > 0) {
      this.oBaseGrid.isOpenPrint = true;
    }
  }

  /**
   * 执行打印
   */
  public doPrint() {
    const oBaseGrid = this.oBaseGrid;
    oBaseGrid.isOpenPrint = false;

    const printSrv: number = oBaseGrid?.selectedPrintTemp['report_servers'];
    const reportID: string = oBaseGrid?.selectedPrintTemp['f_code'];
    // 积木
    if (printSrv === 0) {
      let url = `${oBaseGrid.$config.reportURL}view/${reportID}`;
      url += `?token=${oBaseGrid.$store.state.User.token}`;
      // 勾选数据
      const selectedIDs = this.grid
        .getCheckboxRecords()
        .filter(el => {
          return !!el.id;
        })
        .map(el => {
          return el.id;
        });
      if (selectedIDs.length > 0) {
        url += `&id=${selectedIDs.join(',')}`;
      }
      window.open(url);
    }
  }

  public getFields(): Set<string> {
    const res: Set<string> = new Set();
    const columns = this.grid.getTableColumn().fullColumn;
    columns.forEach(el => {
      if (el.field) {
        res.add(el.field);
        if (el.field.indexOf('|') > -1) {
          const realField = el.field.split('|')[1];
          res.add(realField);
        }
      }
    });
    return res;
  }

  public getRegEventName(type: 'send' | 'receive', eventName: string): string {
    for (const itm of this.oBaseGrid.regCustEventName as Array<
      N_oBaseGrid.I_regCustEventName
    >) {
      if (type === 'receive' && itm?.receive) {
        if (itm.receive.source === eventName) {
          return itm.receive.target;
        }
      }
      if (type === 'send' && itm?.send) {
        if (itm.send.source === eventName) {
          return itm.send.target;
        }
      }
    }
    return undefined;
  }

  public apiEditLock(p: {
    funID: string;
    cmd: 'lock' | 'unLock';
    rowID: string;
    key: string;
  }): Promise<[ifs.I_setDataRes, string]> {
    return Tsrv.standardPostReq<ifs.I_setDataRes, any>(p, Tsrv.url.editLock);
  }

  // 单行加解销，全布解锁 unLockAll 一般只用加锁
  public handleEditLock(row: any, cmd: 'lock' | 'unLock'): Promise<boolean> {
    return new Promise((resole, reject) => {
      if (this.oBaseGrid.isEditable) {
        const key = row.id;
        const funID = this.getFunID();
        if (!this.editLockNum.has(row.id)) {
          this.apiEditLock({ funID, key, rowID: row.id, cmd })
            .then(([res, err]) => {
              console.info(err ?? res.msg);
              if (err) {
                resole(false);
              }
              if (!res.success) {
                // this.oBaseGrid.$msg(res.msg);
                resole(false);
              } else {
                this.editLockNum.set(row.id, {
                  funID,
                  key,
                  rowID: row.id,
                  cmd
                });
                cmd === 'lock'
                  ? Tsrv.TlockInfo.add({
                      funID,
                      rowID: row.id,
                      key
                    })
                  : Tsrv.TlockInfo.removeLockInfoByFunID(funID);
                resole(true);
              }
              if (cmd === 'unLock') {
                this.editLockNum.delete(row.id);
              }
            })
            .catch(err => {
              resole(false);
              console.error(err);
            });
        }
      }
    });
  }

  public unLockALL() {
    if (this.oBaseGrid.isUseEditLock) {
      this.editLockNum.forEach(el => {
        const _el = Tsrv.utils.clone(el);
        _el.cmd = 'unLock';
        this.apiEditLock(_el)
          .then(([res, err]) => {
            // console.info(err ?? res.msg);
            this.editLockNum.delete(el.rowID);
          })
          .catch(err => {
            console.error(err);
          });
      });

      this.oBaseGrid.isLoadEditLock = false;
    }
  }

  // 会话消息 / 字段事件 处理 serviceData用于
  public interactionMsgHandle(
    msg: N_oInteraction.I_msg,
    resData: any = null,
    serviceData: any = null,
    isShowMsg: boolean = true
  ) {
    if (Tsrv.utils.noValue(msg)) {
      return;
    }
    const obj = new ts.T_interaction();
    const res = obj.parseMsg(msg);
    if (res.isErr()) {
      this.oBaseGrid.$msg(res.errmsg);
      throw new Error(res.errmsg);
    } else {
      const interactionCf = res.getReturnData('conf');
      // 处理 cmd
      switch (interactionCf.cmd) {
        // ————————————后面全部替换————————————————————————————
        case N_oInteraction.V_cmd.FIELD_EVENT: {
          this.handleFieldEvent(interactionCf['fieldSettings']).then(r => {
            if (r) {
              this.interactionEventHandle(msg?.next);
            }
          });
          break;
        }
        case N_oInteraction.V_cmd.JUMP_TO_FUN:
          this.handleJumpToFun(interactionCf).then(r => {
            if (r) {
              this.interactionEventHandle(msg?.next);
            }
          });
          break;
        case N_oInteraction.V_cmd.EXECUTE_ACTIONS: // 执行组件动作
          this.handleFrontendActions(interactionCf).then(r => {
            if (r) {
              this.interactionEventHandle(msg?.next);
            }
          });
          break;
        case N_oInteraction.V_cmd.SEARCH_FILTER:
          this.setSearchFilter(interactionCf).then(r => {
            if (r) {
              this.interactionEventHandle(msg?.next);
            }
          });
          break;
        // ————————————————————————————————————————————————————————————————————————
        // 统一替换为 “前端行为”
        case N_oInteraction.V_cmd.FRONTEND_BEHAVIOR:
          this.interactiveBehavior(interactionCf).then(resp => {
            if (resp) {
              this.interactionEventHandle(msg?.next);
            }
          });
          break;
        default:
          Tsrv.utils
            .createModal('oInteraction', interactionCf)
            .then(r => {
              this.interactionEventHandle(msg.next, { resp: r });
            })
            .catch(e => {
              console.error(e);
              this.oBaseGrid.$msg(e);
            });
          break;
      }
    }
  }

  /**
   * @description: 事件交互（next执行）
   * @param {any} params
   * @param {any} next
   * @return {*}
   * @author: swc
   * @Date: 2024-05-24 10:10:08
   * @LastEditors: swc
   * @LastEditTime: Do not edit
   */
  interactionEventHandle(next: any = null, params: any = {}) {
    const ok = next?.ok;
    const cancel = next?.cancel;
    if (!Tsrv.noValue(params)) {
      // 弹窗式交互行为
      const p = params?.resp;
      if (p?.action) {
        if (p.action === 'confirm') {
          if (ok) {
            if (ok?.spName) {
              this.handleInteractionParams(ok?.spParams, params);
              this.doEvent(ok.spName, params);
            }
            if (ok?.actions) {
              this.handleInteractiveBehaviors(ok.actions);
            }
          }
        } else if (p.action === 'cancel') {
          if (cancel) {
            if (cancel?.spName) {
              this.handleInteractionParams(cancel?.spParams, params);
              this.doEvent(cancel.spName, params);
            }
            if (cancel?.actions) {
              this.handleInteractiveBehaviors(cancel.actions);
            }
          }
        } else if (p.action === 'customBtn') {
          const data = p?.data;
          if (!Tsrv.noValue(data) && !Tsrv.noValue(data?.spName)) {
            this.doEvent(data.spName, params);
          }
        }
      }
    } else {
      // 非弹窗交互  默认执行 next中 的 OK下的行为
      if (ok) {
        if (ok?.spName) {
          this.handleInteractionParams(ok?.spParams, params);
          this.doEvent(ok.spName, params);
        }
        if (ok?.actions) {
          this.handleInteractiveBehaviors(ok.actions);
        }
      }
    }
  }

  //
  private handleInteractionParams(settingP: any = null, defaultP: any = null) {
    // 交互next 传参。如果json中返回的没有 spParams
    if (Tsrv.utils.noValue(settingP)) {
      if (Object.prototype.hasOwnProperty.call(defaultP, 'resp')) {
        if (Tsrv.utils.noValue(defaultP?.resp?.data))
          defaultP.resp.data = this.getSelectedData('select');
      } else {
        defaultP['funName'] = this.getFunName();
        defaultP['data'] = {};
        defaultP.from = 'nextSp';
        const rows = this.grid.getCheckboxRecords().filter(el => {
          return !!el.id;
        });
        this.checkJsonField(rows);
        defaultP.data[this.tableName] = rows.map(el => {
          return el.id;
        });
        defaultP.data['rows'] = {};
        defaultP.data['rows'][this.tableName] = rows;
        defaultP.data['custBtns'] = [];
        this.oBaseGrid.toolbar['addon'].forEach(el => {
          defaultP.data['custBtns'].push({ title: el.title, status: el.auth });
        });
      }
      // return defaultP;
    } else {
      // 有 spParams 的处理
      if (Object.prototype.hasOwnProperty.call(defaultP, 'resp')) {
        settingP.forEach((el: any, idx: number) => {
          if (el?.key) {
            // if (el.originType === 'dynamic') { // 动态值:dynamic，静态值:static
            if (el.key.indexOf('$') > -1) {
              // 动态值:dynamic，静态值:static
              // defaultP.resp.data[el.key.split('$')[1] ?? `key${idx}`] = this.getSpParamsByDynamic(el.value);
              this.getSpParamsByDynamic(
                el.value,
                defaultP.resp.data,
                el.key.split('$')[1] ?? `key${idx}`
              );
            } else {
              defaultP.resp.data[el.key ?? `key${idx}`] = el.value;
            }
          }
        });
        // for (let index = 0; index < array.length; index++) {
        //   const element = array[index];

        // }
        // return defaultP;
      } else {
        // defaultP = this.getSelectedData('select');
        defaultP['funName'] = this.getFunName();
        defaultP['data'] = {};
        defaultP.from = 'nextSp';
        const rows = this.grid.getCheckboxRecords().filter(el => {
          return !!el.id;
        });
        this.checkJsonField(rows);
        defaultP.data[this.tableName] = rows.map(el => {
          return el.id;
        });
        defaultP.data['rows'] = {};
        defaultP.data['rows'][this.tableName] = rows;
        defaultP.data['custBtns'] = [];
        this.oBaseGrid.toolbar['addon'].forEach(el => {
          defaultP.data['custBtns'].push({ title: el.title, status: el.auth });
        });
        if (Array.isArray(settingP)) {
          settingP.forEach((ell: any, iidx: number) => {
            if (ell?.key) {
              if (ell.key.indexOf('$') > -1) {
                // 动态值:dynamic，静态值:static
                // defaultP.data[ell.key.split('$')[1] ?? `key${iidx}`] = this.getSpParamsByDynamic(ell.value);
                this.getSpParamsByDynamic(
                  ell.value,
                  defaultP.resp.data,
                  ell.key.split('$')[1] ?? `key${iidx}`
                );
              } else {
                defaultP.data[ell.key ?? `key${iidx}`] = ell.value;
              }
            }
          });
        }
        // return defaultP;
      }
    }
  }

  public searchFilterChange(p: any = null) {
    const actions = this.getActionCfg();
    const spName = actions?.searchFilter ?? '';
    // 条件仅 p.type === 'search' 可用
    if (
      !Tsrv.noValue(p) &&
      !(p.listenType === this.oBaseGrid.listenType || p.type === 'search')
    ) {
      return;
    }
    if (Tsrv.noValue(spName)) {
      return;
    }
    // 是否是新增数据时将诶收到的数据 _file_info_id_ 和 _sort_
    const pRowData = p?.option?.autoCompleteInfo?.data ?? {};
    if (
      !Tsrv.noValue(pRowData) &&
      (!Object.prototype.hasOwnProperty.call(pRowData, '_file_info_id_') ||
        !Object.prototype.hasOwnProperty.call(pRowData, '_sort_'))
    ) {
      return;
    }
    const params = this.getSelectedData();
    params.data['searchFilter'] = null;
    if (!Tsrv.noValue(p)) {
      const searchFilter = {
        iField: p?.content?.ukey ?? '',
        iTableName: p?.option?.autoCompleteInfo?.toTable ?? '',
        pField: p?.content?.ikey ?? '',
        pTableName: p?.option?.autoCompleteInfo?.table ?? '',
        value: p?.option?.autoCompleteInfo?.key ?? '',
        pRowData: p?.option?.autoCompleteInfo?.data ?? {}
      };
      params.data['searchFilter'] = searchFilter;
    }
    params.title = spName;
    params.from = 'searchFilter';
    setTimeout(() => {
      this.doEvent(spName, params, null, false);
    }, 0);
    // this.doEvent(spName, params, null, false);
  }

  private setSearchFilter(obj: object): any {
    return new Promise((resolve, reject) => {
      Object.keys(obj).forEach(key => {
        if (key !== 'cmd' && JSON.stringify(obj[key]).indexOf('$') > -1) {
          this.fieldsSearchFilter.set(key, obj[key]);
        }
      });
      resolve(true);
    });
  }

  public getFieldFilter(type: string): any {
    return this.fieldsSearchFilter.get(type);
  }

  private getSpParamsByDynamic(re: any, o: object, k: string) {
    if (Tsrv.utils.isJSONString(re)) {
      re = JSON.parse(re);
    }
    switch (re.cmd) {
      case 'getAutoNum':
        this.getAutoNum(re.params, o, k);
        break;
      default:
        break;
    }
  }

  private async getAutoNum(re: any, o: object, k: string) {
    const [resp, err] = await Tsrv.getAutoNum(re.funName, re.field);
    if (err) {
      this.oBaseGrid.$msg(err);
      o[k] = '';
    } else {
      o[k] = resp?.data?.code;
    }
  }

  // 处理交互消息 确认/取消 后动作
  private handleInteractiveBehaviors(actions: object): Promise<boolean> {
    return new Promise((resolve, reject) => {
      Object.keys(actions).forEach(key => {
        switch (key) {
          case 'isRefresh':
            if (actions['isRefresh']) this.oBaseGrid.commitEvent('reload');
            resolve(true);
            break;
          case 'isEdit':
            this.oBaseGrid.commitEvent('edit', actions[key]);
            resolve(true);
            break;
          case 'editable':
            this.oBaseGrid.commitEvent('edit', actions[key]);
            resolve(true);
            break;
          case 'filter':
            this.setFilterByAction(actions[key]);
            resolve(true);
            break;
          case 'download':
            this.downloadEvent(actions[key]);
            resolve(true);
            break;
          case 'crossSystem':
            this.handleCrossSystem(actions[key]);
            resolve(true);
            break;
          case 'chartView':
            this.handleChartView(actions[key]);
            resolve(true);
            break;
          case 'setCustomBtnStatus':
            if (actions[key] && !Tsrv.utils.noValue(actions[key])) {
              const addon = this.oBaseGrid.toolbar['addon'];
              const customBtnStatus = actions[key].filter(el => {
                return addon.some(el2 => el2.title === el.title);
              });
              customBtnStatus.forEach(el => {
                if (Object.prototype.hasOwnProperty.call(el, 'status')) {
                  this.setCustBtnStatus(el.title, el.status);
                }
              });
            }
            resolve(true);
            break;
          // 发送bus事件
          case 'events':
            if (!Tsrv.noValue(actions[key]) && Array.isArray(actions[key])) {
              const events = actions[key];
              events.forEach(event => {
                if (Tsrv.utils.isJSONString(event.params)) {
                  event.params = JSON.parse(event.params);
                }
                Tsrv.reliablySendingBusEvent(
                  event.name,
                  this.oBaseGrid.$bus,
                  10,
                  100,
                  event.params
                );
              });
            }
            resolve(true);
            break;
          // 字段设置（1：指定值临时改变、禁止编辑。2：添加basegrid的rule）
          case 'fieldSettings':
            this.handleFieldEvent(actions[key])
              .then(res => {
                if (res) {
                  resolve(true);
                }
              })
              .catch(() => {});
            break;
          default:
            break;
        }
      });
    });
  }

  // 处理交互消息 确认/取消 后动作
  private handleInteractionAcions(actions: object, e?: any) {
    Object.keys(actions).forEach(key => {
      switch (key) {
        case 'isRefresh':
          if (actions['isRefresh']) this.oBaseGrid.commitEvent('reload');
          break;
        case 'isEdit':
          this.oBaseGrid.commitEvent('edit', actions['isEdit']);
          break;
        case 'setCustomBtnStatus':
          if (
            actions['setCustomBtnStatus'] &&
            !Tsrv.utils.noValue(actions['setCustomBtnStatus'])
          ) {
            const addon = this.oBaseGrid.toolbar['addon'];
            const customBtnStatus = actions['setCustomBtnStatus'].filter(el => {
              return addon.some(el2 => el2.title === el.title);
            });

            customBtnStatus.forEach(el => {
              if (Object.prototype.hasOwnProperty.call(el, 'status')) {
                this.setCustBtnStatus(el.title, el.status);
              }
            });
          }
          break;
        case 'events':
          if (
            !Tsrv.noValue(actions['events']) &&
            Array.isArray(actions['events'])
          ) {
            const events = actions['events'];
            events.forEach(event => {
              if (Tsrv.utils.isJSONString(event.params)) {
                event.params = JSON.parse(event.params);
              }
              Tsrv.reliablySendingBusEvent(
                event.name,
                this.oBaseGrid.$bus,
                10,
                100,
                event.params
              );
            });
          }
          break;
        case 'styleRules':
          if (
            !Tsrv.noValue(actions['styleRules']) &&
            Array.isArray(actions['styleRules'][0])
          ) {
            this.oBaseGrid.setRules(
              Tsrv.noValue(actions['styleRules'][0].styleRule)
                ? this.oBaseGrid.config.rules
                : actions['styleRules'][0].styleRule
            );
          }
          break;
        default:
          break;
      }
    });
  }

  private interactiveBehavior(msg: any): Promise<any> {
    return new Promise((resolve, reject) => {
      const msgContent = Tsrv.utils.clone(msg);
      const frontendBehavior = msgContent['frontendBehavior'];
      if (!Tsrv.noValue(frontendBehavior)) {
        const haviorPs = Object.keys(frontendBehavior);
        if (
          haviorPs.indexOf('funConfs') > -1 ||
          haviorPs.indexOf('action') > -1
        ) {
          let behaviors = {};
          const action = frontendBehavior['action'];
          const funConfs = frontendBehavior['funConfs'];
          if (!Tsrv.noValue(funConfs)) {
            !Tsrv.noValue(funConfs[this.tableName]) &&
              (behaviors = Object.assign(behaviors, funConfs[this.tableName]));
          }
          if (!Tsrv.noValue(action)) {
            behaviors = Object.assign(behaviors, action);
          }
          this.handleInteractiveBehaviors(behaviors).then(res => {
            if (res) {
              resolve(true);
            } else {
              resolve(false);
            }
          });
        } else {
          console.error('behavior is null');
          resolve(false);
        }
      } else {
        console.error('msgContent is null');
        resolve(false);
      }
    });
  }

  // 处理字段事件
  public handleFieldEvent(res: any) {
    return new Promise((resolve, reject) => {
      const cell = res['cell'];
      if (!Tsrv.noValue(cell)) {
        // 字段事件—— 修改 setting 的逻辑
        const setting = cell['setting'];
        if (!Tsrv.noValue(setting) && !Tsrv.noValue(setting['options'])) {
          const options = setting['options'];
          // 要修改的 项
          if (!Tsrv.noValue(options) && Array.isArray(options)) {
            const fullData = this.getGrid().getTableData().fullData;
            for (let k = 0; k < options.length; k++) {
              const option = options[k];
              if (Tsrv.noValue(option['id'])) {
                continue;
              }
              // 更新字段
              if (
                !Tsrv.noValue(option['setValue']) &&
                Array.isArray(option['setValue'])
              ) {
                option['setValue'].forEach(field => {
                  for (let i = 0; i < fullData.length; i++) {
                    if (fullData[i].id === option.id) {
                      fullData[i][field['key']] = field['value'];
                      break;
                    }
                  }
                });
              }
              // 字段禁用状态 （后续改为样式）
              if (
                !Tsrv.noValue(option['setStyle']) &&
                Array.isArray(option['setStyle'])
              ) {
                /* 注：现在实现方案是：利用vxetable的rules功能，
                    ——未来需要优化改为：修改表格的指定input的样式效果
                  （实现方案：this.oBasegrid.tableColumns中的editRender.prop
                  （在当前input中可获得row数据，根据row数据id来判断是否使用该样式效果））
                  */
                option['setStyle'].forEach(field => {
                  // 设置 rules 方式实现
                  const cellEditCfg = this.oBaseGrid.cellEditCfg;
                  const findField = cellEditCfg.find(
                    it => it.field === field['key']
                  );
                  if (Tsrv.noValue(findField)) {
                    cellEditCfg.push({
                      field: field['key'],
                      editable: !field['value']?.isDisable,
                      conditions: {
                        field: 'id',
                        operator: 'has',
                        type: 'text',
                        value: option.id
                      }
                    });
                  }
                });
              }
              // editrender 写法 （建议）
              // const columns = this.oBaseGrid.tableColumns;
              // Object.keys(fieldsStatus).forEach(item => {
              //   if (item.indexOf('.') > -1) {
              //     const field = item.split('.')[1];
              //     let targetField;
              //     for (let i = 0; i < columns.length; i++) {
              //       // if (columns[i]?.field && columns[i]?.field === field) {
              //       if (columns[i]?.title && columns[i]?.title === field) {
              //         targetField = columns[i];
              //         break;
              //       } else if (Tsrv.utils.has(columns[i], 'children')) {
              //         const children = columns[i].children;
              //         for (let j = 0; j < children.length; j++) {
              //           // if (children[j]?.field && children[j]?.field === field) {
              //           if (children[j]?.title && children[j]?.title === field) {
              //             targetField = children[j];
              //             break;
              //           }
              //         }
              //       }
              //     }
              //     if (!Tsrv.utils.noValue(targetField.editRender.props)) {
              //       targetField.editRender.props.disabled = fieldsStatus[item];
              //     }
              //   }
              // });
            }
          }
        }
        // 字段事件—— 修改 rules 的逻辑
        const rules = cell['rules'];
        if (!Tsrv.noValue(rules) && Array.isArray(rules)) {
          rules.forEach(rule => {
            this.addVxegridRules('cell', rule);
          });
        }
      }
      // 行事件—— 修改 rules 的逻辑
      const row = res['row'];
      if (!Tsrv.noValue(row)) {
        const rules = row['rules'];
        if (!Tsrv.noValue(rules) && Array.isArray(rules)) {
          rules.forEach(rule => {
            this.addVxegridRules('row', rule);
          });
        }
      }
      // 列事件—— 修改 rules 的逻辑
      const column = res['column'];
      if (!Tsrv.noValue(column)) {
        const rules = column['rules'];
        const fieldFilter = column['fieldFilter'];
        const config = column['config'];
        if (!Tsrv.noValue(rules) && Array.isArray(rules)) {
          rules.forEach(rule => {
            this.addVxegridRules('column', rule);
          });
        }
        if (!Tsrv.noValue(fieldFilter)) {
          this.setFieldFilter(fieldFilter);
        }
        if (!Tsrv.noValue(config)) {
          this.setColumnConfig(config);
        }
      }
      resolve(true);
    });
  }

  // 添加 表格 规则信息
  public addVxegridRules(to: 'cell' | 'column' | 'row', rule: any) {
    let editCfg = null;
    let styleCfg = null;

    if (to === 'cell') {
      editCfg = this.oBaseGrid.cellEditCfg; // 表格单元格编辑配置
      styleCfg = this.oBaseGrid.cellStyleCfg; // 表格单元格编辑配置
    } else if (to === 'column') {
      editCfg = this.oBaseGrid.columnEditCfg; // 表格列编辑配置
      styleCfg = this.oBaseGrid.columnStyleCfg; // 表格列编辑配置
    } else if (to === 'row') {
      editCfg = this.oBaseGrid.rowEditCfg; // 表格行编辑配置
      styleCfg = this.oBaseGrid.rowStyleCfg; // 表格行编辑配置
    } else {
      return;
    }
    if (!Tsrv.noValue(rule?.editRules) && Array.isArray(rule.editRules)) {
      editCfg.push(...rule.editRules);
    }
    if (!Tsrv.noValue(rule?.styleRules) && Array.isArray(rule.styleRules)) {
      styleCfg.push(...rule.styleRules);
    }
    // const cellStyleCfg = this.oBaseGrid.cellStyleCfg;
    // cellStyleCfg.push({
    //   field: 'title',
    //   style: {
    //     backgroundColor: '#A4F02D !important',
    //     fontWeight: 'bold',
    //     fontStyle: 'italic',
    //     textDecoration: 'underline'
    //   },
    //   conditions: [
    //     { field: 'footer_method', type: 'number', operator: '=', value: '1' }
    //   ]
    // });
  }

  // 设置注入的过滤条件
  public setFilterByAction(filter: any) {
    let f = null;
    if (!Tsrv.noValue(filter)) {
      if (JSON.stringify(filter).indexOf('$') > -1) {
        f = new ts.T_filter();
        f.filter = filter;
      } else if (Array.isArray(filter)) {
        f = filter;
      }
      this.setInjectFilter(f);
    }
  }

  // 设置字段过滤
  public setFieldFilter(fieldFilter: any) {
    Object.keys(fieldFilter).forEach(key => {
      this.fieldsSearchFilter.set(key, fieldFilter[key]);
    });
  }

  // 列配置
  private setColumnConfig(columns: Array<any>) {
    const oBaseGrid = this.oBaseGrid;
    if (Array.isArray(columns)) {
      for (let i = 0; i < columns.length; i++) {
        const column = columns[i];
        const field = column['field'];
        if (!field) {
          continue;
        }
        if (!Tsrv.noValue(column['visible'])) {
          oBaseGrid.setColumnVisible(field, column['visible']);
        }
        if (!Tsrv.noValue(column['operateCol'])) {
          const conf = column['operateCol'];
          if (!Tsrv.noValue(conf['usable'])) {
            const usable = oBaseGrid.operateColumnConfig.usable;
            conf['usable'] ? usable.add(field) : usable.delete(field);
          }
          if (!Tsrv.noValue(conf['display'])) {
            const display = oBaseGrid.operateColumnConfig.display;
            conf['display'] ? display.add(field) : display.delete(field);
          }
        }
      }
    }
  }

  // 下载
  public downloadEvent(info: any) {
    if (!Tsrv.noValue(info)) {
      const oBaseGrid = this.oBaseGrid;
      const fName = info?.fileName || null;
      const fPath = info?.path || null;
      const fileInfo = info?.fileInfo ?? null;
      const downloadFiles = [];
      // 1、通过文件信息来下载 fileName path
      if (!Tsrv.noValue(fName) && !Tsrv.noValue(fPath)) {
        const file = {
          fName,
          fPath,
          fileName: fName
        };
        downloadFiles.push(file);
      }
      // 2、通过表格数据来下载
      if (!Tsrv.noValue(fileInfo)) {
        const id = fileInfo.id;
        const field = fileInfo.field;
        const fullData = this.getGrid().getTableData().fullData;
        const row = fullData.find(el => el.id === id);
        if (Tsrv.noValue(row)) {
          oBaseGrid.$msg(Tsrv.getI18nByValue('未找到该数据'));
          return;
        }
        let value = row[field];
        if (Tsrv.utils.isJSONString(value)) {
          value = JSON.parse(value);
        }
        const files = value?.files;
        if (!Tsrv.noValue(files) && Array.isArray(files)) {
          for (let i = 0; i < files.length; i++) {
            const el = files[i];
            if (
              Tsrv.noValue(el?.libFileName) ||
              Tsrv.noValue(el?._content_) ||
              Tsrv.noValue(el?.fileName)
            ) {
              continue;
            }
            const file = {
              fName: el.libFileName,
              fPath: el._content_,
              fileName: el.fileName
            };
            downloadFiles.push(file);
          }
        }
      }
      if (downloadFiles.length === 0) return;
      downloadFiles.forEach(item => {
        const dwn = new ts.T_downloadArg();
        dwn.setFileName(item.fName).setPath(item.fPath);
        Tsrv.download(dwn, true, item.fileName)
          .then(r => {
            if (r.err) {
              oBaseGrid.$msg(r.err);
            }
          })
          .catch(err => {
            oBaseGrid.$msg(err);
          });
      });
    }
  }

  // 事件交互—— 跨系统交互
  public handleCrossSystem(p: any) {
    const mode = p?.mode ?? 'tab';
    const url = p?.url ?? '';
    if (Tsrv.noValue(url)) {
      return;
    }
    switch (mode) {
      case 'tab':
        window.open(url);
        break;
      case 'popup':
        Tsrv.utils
          .createModal('o-iframe', {
            modalSize: [p?.width ?? 560, p?.height ?? 420],
            modalTitle: p.title ?? Tsrv.getI18nByValue('外部系统'),
            config: {
              url
            }
          })
          .then(res => {});
        break;
      default:
        break;
    }
  }

  /**
   * @description 事件交互——图表
   * @param p
   */
  private handleChartView(p: any) {
    Tsrv.utils
      .createModal('o-chart-view', {
        modalSize: [p?.modal?.width ?? 660, p?.modal?.height ?? 520],
        modalTitle: p?.modal?.title ?? Tsrv.getI18nByValue('图表视图'),
        config: {
          // type: p?.type,
          // dataSource: p?.dataSource
          ...p
        }
      })
      .then(res => {});
  }

  // QBE 查询
  private compBoxItem: Map<string, any> = new Map<string, any>();

  public regCompItem(compBoxInfo: ifs.I_compBoxInfo, key: string) {
    const compID = compBoxInfo.compID;
    const compBox = compBoxInfo.TcompBox;
    this.compBoxItem.set(key, compBox.getCompMergeName(compID, 'oBaseForm'));
  }

  public getCompItemByName(key: number | string) {
    return this.compBoxItem.get(`${key}`);
  }

  public btnEdit(p: any) {
    this.editorStatus = p ? 'modify' : 'none';
    this.oBaseGrid.editTable(p);
  }

  // 获取表格的自定义按钮状态
  public getCustBtnStatus() {
    const btns = this.oBaseGrid.toolbar['addon'];
    let hasReadStatusSet = false;
    btns.forEach(btn => {
      if (btn?.readCurrentStatus) {
        hasReadStatusSet = true;
      }
    });
    if (hasReadStatusSet) {
      const gpd = new ts.T_getPartDataArg();
      const filter = {
        fun_name: this.funName
      };
      gpd
        .setFilter(filter)
        .setFunName(Tsrv.globalVar.funName.SYS_CUSTOMBTN_STATUS)
        .setTableName(Tsrv.globalVar.funName.SYS_CUSTOMBTN_STATUS)
        .setDbType(Tsrv.globalVar.dbType.MYSQL)
        .setLang(this.getLang())
        .setRule({} as ifs.I_rule);
      gpd.setPage(1, 99999);
      Tsrv.getData(gpd).then(([b, res, rows, err]) => {
        if (!b && err) {
          this.oBaseGrid.$msg(err ?? res.msg);
        } else {
          const customBtns = [];
          if (!Tsrv.utils.noValue(rows)) {
            rows.forEach(el => {
              customBtns.push({
                title: el.button_name,
                status: !el.disabled,
                id: el.id
              });
            });
          }
          this.oBaseGrid.customBtnStatus = customBtns;
          if (this.oBaseGrid.toolbar['addon'].length > 0)
            this.oBaseGrid.toolbar['addon'].forEach(el => {
              // el.auth = !!data[el.title];
              const btn = customBtns.find(el2 => el2.title === el.title);
              if (el?.readCurrentStatus === true && !Tsrv.utils.noValue(btn)) {
                this.handleCustBtnStatus(el.title, 'auth', btn.status);
              }
            });
        }
      });
    }
  }

  // 设置表格的自定义按钮状态
  public setCustBtnStatus(title: string, status: boolean) {
    const btn = this.oBaseGrid.toolbar['addon'].find(el => el.title === title);
    if (btn?.readCurrentStatus) {
      const ctd = new ts.T_ctdArg();
      ctd
        .setTableName(Tsrv.globalVar.funName.SYS_CUSTOMBTN_STATUS)
        .setDbType(Tsrv.globalVar.dbType.MYSQL)
        .setRule({} as ifs.I_rule);
      // 如果该表格自定义按钮记录中没有此按钮则向表中新增
      const btnStatus = this.oBaseGrid.customBtnStatus.find(
        el2 => el2.title === title
      );
      if (Tsrv.utils.noValue(btnStatus)) {
        const scope = {};
        const insertRecord = [
          { field: 'id', value: Tsrv.getSnowIDFmtStr() },
          { field: 'fun_name', value: this.funName },
          { field: 'button_name', value: title },
          { field: 'disabled', value: status ? 0 : 1 }
        ];
        const bDatas: ifs.I_baseData[] = [];
        const bData = new ts.T_baseData();
        bData
          .setDataRule({} as ifs.I_rule)
          .setFileInfo({})
          .setRowData(...(insertRecord as ifs.I_fv[]));
        bDatas.push(bData);
        ctd.setInsRecDataMany(scope, ...bDatas);
      } else {
        //  如果该表格自定义按钮记录中有此按钮则修改
        // 获取的自定义按钮状态 与 要修改的状态 相等时不做任何操作
        if (btnStatus.status === status) {
          return;
        }
        const updateRecord = [{ field: 'disabled', value: status ? 0 : 1 }];
        const filter = { id: btnStatus.id };
        const ctdUpdDatas: ifs.I_ctdUpdData[] = [];
        const ctdUpdData = new ts.T_ctdUpdData();
        ctdUpdData.setDataRule({} as ifs.I_rule).setFileInfo({});
        // filter = { id: btnStatus.id };
        ctdUpdData.setFilter(filter);
        ctdUpdData.setRowData(...(updateRecord as ifs.I_fv[]));
        ctdUpdDatas.push(ctdUpdData);
        ctd.setUpdRecDataMany(...ctdUpdDatas);
      }
      Tsrv.batRows(ctd).then(resp => {
        const [b, res, msg] = resp;
        msg && this.oBaseGrid.$msg(msg);
        if (b) {
          // resolve(true);
          this.handleCustBtnStatus(title, 'auth', status);
        } else {
          // reject();
        }
      });
    } else {
      this.handleCustBtnStatus(title, 'auth', status);
    }
  }

  /**
   * 执行自定义功能
   */
  public doCustomBtnAction(title: string, action: string) {
    // 功能配置中转
    if (action === Tsrv.globalVar.spName.addFunSetup) {
      Tsrv.utils.createModal('o-setup-panel', null);
      return;
    }

    const params = this.getSelectedData('select');
    params.title = title;
    params.from = 'customButton';

    // 西飞生成喷漆编码向导
    if (action === Tsrv.globalVar.spName.genPaintCode) {
      Tsrv.utils.createModal('c-paint-code-guide', params);
      return;
    }

    this.doEvent(action, params);
  }

  /**
   * 执行控件事件
   */
  public doOControlAction(action: string, data: any) {
    // 功能配置中转
    if (action === Tsrv.globalVar.spName.addFunSetup) {
      Tsrv.utils.createModal('o-setup-panel', null);
      return;
    }
    const params = {
      funName: this.getFunName(),
      title: data?.field || '',
      from: 'oControl',
      data: {},
      parentID: this.oBaseGrid.linkParent.rowID || 0
    };
    const rows = [];
    if (data?.row) {
      rows.push(data.row);
    }
    this.checkJsonField(rows);
    params.data[this.tableName] = rows.map(el => {
      return el.id;
    });
    params.data['rows'] = {};
    params.data['rows'][this.tableName] = rows;

    this.doEvent(action, params);
  }

  // 导出xml 临时版，（导出xml适合 添加 到 导入导出功能 中）
  public async exportXml() {
    const params = {
      funName: this.funName,
      lang: this.oBaseGrid.$i18n.locale,
      filter: {},
      fields: []
    };
    const [_res, _err] = await Tsrv.standardPostReq<ifs.I_setDataRes, any>(
      params,
      Tsrv.lexicon.url.exportXml
    );
    if (_err || !_res.success) {
      // this.oBaseGrid.$msg()
      console.error(Tsrv.getI18nByValue('导出xml文件错误'));
    } else {
      const dwn = new ts.T_downloadArg();
      dwn.setFileName(_res.data.xml).setPath('temp');
      Tsrv.download(dwn, true, `${Tsrv.getI18nBySrv(this.funName)}`)
        .then(r => {
          if (r.err) {
            console.error(Tsrv.getI18nByValue('下载xml文件错误'));
          }
        })
        .catch(err => {
          console.error(Tsrv.getI18nByValue('下载xml文件错误'));
        });
    }
  }

  // 跳转指定功能（单据）
  public handleJumpToFun(p: any) {
    // 返回值约定 （配置表 校验是否配置跳转功能，是在前端配置还是在后端配置？）
    return new Promise((resolve, reject) => {
      // if (!Tsrv.getx(p, 'enable', false)) {
      //   this.oBaseGrid.$msg(Tsrv.getI18nByValue('该功能未配置跳转'));
      //   return;
      // }
      this.oBaseGrid.$store
        .dispatch('getLayoutConfigAsync', {
          funid: null,
          field: p.funName,
          type: 'component'
        })
        .then((res: any) => {
          const funType = res?.current?.name;
          if (!Tsrv.noValue(funType)) {
            this.oBaseGrid.addTabFunc(p.funName).then((resp: any) => {
              resolve(resp);
              if (funType.toLowerCase() === 'basepanel') {
                // 如果有handleSearchTo函数 （可修改：判断是否为单据类型的功能）
                const that = resp.$children[0].$children[0];
                if (
                  that &&
                  typeof that?.handleSearchTo === 'function' &&
                  Tsrv.utils.isNumber(p.pageNo)
                ) {
                  const timeout = p.pageNo === 0 ? 800 : 0;
                  setTimeout(() => {
                    if (p.pageNo === 0) {
                      that.commitEvent('insert_actived');
                    } else {
                      that.handleSearchTo(p.pageNo).then(r => {
                        if (r && !Tsrv.utils.noValue(p?.actions)) {
                          that.GT_command.handleInteractionAcions(p.actions);
                        }
                      });
                    }
                  }, timeout);
                }
              } else if (funType.toLowerCase() === 'customfun') {
                const that = resp.$children[0].$children[0];
                if (that && typeof that?.jumpToCustomFun === 'function') {
                  that.jumpToCustomFun(p);
                }
              }
            });
          }
        });
    });
  }

  private handleFrontendActions(res) {
    return new Promise((resolve, reject) => {
      const actions = Tsrv.utils.clone(res.actions);
      this.handleInteractionAcions(actions);
      resolve(true);
    });
  }

  // 获取活跃数据（即选中的数据--表体选中的id）
  public getSelectedData(
    type: 'select' | 'current' | 'customRows' = 'select',
    customRows?: Array<any>
  ) {
    const params = {
      funName: this.getFunName(),
      title: '',
      from: '',
      data: {},
      parentID: this.oBaseGrid.linkParent.rowID || 0
    };
    if (type === 'select') {
      const rows = this.grid.getCheckboxRecords().filter(el => {
        return !!el.id;
      });
      this.checkJsonField(rows);
      params.data[this.tableName] = rows.map(el => {
        return el.id;
      });
      params.data['rows'] = {};
      params.data['rows'][this.tableName] = rows;
    } else if (type === 'current') {
      const rows = [];
      if (!Tsrv.noValue(this.grid.getCurrentRecord())) {
        rows.push(this.grid.getCurrentRecord());
      }
      this.checkJsonField(rows);
      params.data[this.tableName] = [rows[0]?.id];
      params.data['rows'] = {};
      params.data['rows'][this.tableName] = rows;
    } else if (type === 'customRows') {
      const rows = customRows;
      this.checkJsonField(rows);
      params.data[this.tableName] = rows.map(el => {
        return el.id;
      });
      params.data['rows'] = {};
      params.data['rows'][this.tableName] = rows;
    }
    params.data['custBtns'] = [];
    // params.data['rowColomnBtn'] = [];
    this.oBaseGrid.toolbar['addon'].forEach(el => {
      params.data['custBtns'].push({ title: el.title, status: el.auth });
    });
    return params;
  }

  // 检查是否有json字段，如果有则进行处理
  public checkJsonField(rows: Array<any>) {
    const jsonFields = this.oBaseGrid._config.tableColumns
      .filter(item => {
        return item.type === 'json' || item.type === 'mediumtext';
      })
      .map(el => {
        return el.field;
      });
    if (rows && rows.length > 0) {
      rows.forEach(el => {
        if (jsonFields && jsonFields.length > 0) {
          jsonFields.forEach(ell => {
            // if (el[ell] && typeof el[ell] === 'string') {
            if (el && el[ell] && Tsrv.utils.isJSONString(el[ell])) {
              el[ell] = JSON.parse(el[ell]);
            }
          });
        }
      });
    }
  }

  // 启动轮询事件
  public startPollingEvent() {
    this.getPollingEvent().then(([b, res]) => {
      if (b) {
        this.tasker = new ts.T_task(1000); // 默认1秒
        this.taskerInfo = res;
        this.tasker.addTask(this.executePollingEvent);
        if (this.taskerInfo.intervalTime < 1000) {
          this.taskerInfo.intervalTime = 1000;
        }
        this.tasker.switchIntervalTime(this.taskerInfo.intervalTime);
      }
    });
  }

  // 执行轮询事件
  public executePollingEvent = () => {
    const params = this.getSelectedData('current');
    params.title = this.taskerInfo.eventName;
    params.from = 'pollEvent';
    this.doEvent(this.taskerInfo.eventName, params, null, false)
      .then(res => {
        if (
          res &&
          this.taskerInfo.intervalTime !== this.tasker.getIntervalTime()
        ) {
          this.tasker.switchIntervalTime(this.taskerInfo.intervalTime);
        } else {
          this.tasker.switchIntervalTime(5000);
        }
      })
      .catch(err => {
        if (!err) this.tasker.switchIntervalTime(5000);
      });
  };

  private getPollingEvent(): Promise<Array<any>> {
    // _sys_fun_id , _sys_publicprocess_id / m2o|_sys_publicprocess_id|_sys_publicprocess|f_name , interval_time , isopen
    return new Promise(resolve => {
      if (Tsrv.noValue(this.funID)) {
        return;
      }
      const tableName = '_sys_round_robin_info';
      const gpd = new ts.T_getPartDataArg();
      const filters: Array<any> = [
        { _sys_fun_id: { $in: [this.funID] } },
        { isopen: { $in: [1] } }
      ];
      gpd.setFunName(tableName).setLang(Tsrv.store.state.App.language);
      gpd.setPage(1, 99999).setDbType(Tsrv.globalVar.dbType.MYSQL);
      gpd.setFilter({ $and: filters });
      Tsrv.getData<any, ifs.I_getPartDataArg>(gpd)
        .then(([b, res, rows, m]) => {
          if (!b) {
            m && this.oBaseGrid.$msg(m ?? res.msg);
            resolve([false]);
          } else {
            if (!rows || rows.length === 0) {
              resolve([false]);
              return;
            }
            const row: any = rows[0];
            const _P = {
              intervalTime: row['interval_time'] ?? 1000,
              eventName:
                row['m2o|_sys_publicprocess_id|_sys_publicprocess|f_name'] ??
                '_sys_interaction_default_resp'
            };
            resolve([true, _P]);
          }
        })
        .catch(er => {
          console.error('获取用户消息失败', er);
        });
    });
  }

  public stopPollingEvent() {
    if (!Tsrv.noValue(this.tasker)) {
      this.tasker.stopTask();
    }
  }

  // 获取功能配置
  public getCompConfig() {
    return this.oBaseGrid.config;
  }

  // 构建组件协作处理类
  public newTcompCoordination(conf: any) {
    if (!this.oBaseGrid.isCoordination) {
      return;
    }

    // 组件调度
    this.TCoordination = new ts.T_compCoordination(
      conf.name,
      conf.messageConfig,
      {
        setTempToolbarStatusDisabled: (
          p: N_oSetupPanel.N_comps.T_eventCoordinationToolbar
        ) => {
          this.setTempToolbarStatusDisabled(p);
        },
        setTempToolbarStatusUnDisabled: (
          p: N_oSetupPanel.N_comps.T_eventCoordinationToolbar
        ) => {
          this.setTempToolbarStatusUnDisabled(p);
        },
        cleanSubCompData: (
          p: N_oSetupPanel.N_comps.T_eventCoordinationToolbar
        ) => {
          this.oBaseGrid.cleanSubCompData(p);
        },
        setMask: (p: boolean) => {
          this.oBaseGrid.isMask = p;
        }
      }
    );
  }

  // 处理组件协调
  public receEventCoordination(
    m: N_oSetupPanel.N_comps.I_eventCoordinationMsg
  ) {
    if (!this.oBaseGrid.isCoordination) {
      return;
    }
    this.TCoordination.receEventCoordination(m)
      .then(([b, msg]) => {})
      .catch(msg => {
        console.error(msg);
        // this.oBaseGrid.$msg(msg);
      });
  }

  private setTempToolbarStatusDisabled(
    p: N_oSetupPanel.N_comps.T_eventCoordinationToolbar
  ) {
    if (Tsrv.utils.noValue(this.toolbarStatusBak)) {
      this.toolbarStatusBak = Tsrv.utils.clone(this.oBaseGrid.toolbar, true);
      // previous、jumpFirst、next、jumpLast这几个按钮basegrid不具备，暂时注释
      // this.oBaseGrid.toolbar.previous.isDisable = true;
      // this.oBaseGrid.toolbar.jumpFirst.isDisable = true;
      // this.oBaseGrid.toolbar.next.isDisable = true;
      // this.oBaseGrid.toolbar.jumpLast.isDisable = true;
      this.oBaseGrid.toolbar.save.isDisable = true;
      this.oBaseGrid.toolbar.edit.isDisable = true;
      this.oBaseGrid.toolbar.audit.isDisable = true;
      this.oBaseGrid.toolbar.delete.isDisable = true;
      this.oBaseGrid.toolbar.insert.isDisable = true;
      this.oBaseGrid.toolbar.edit.isDisable = true;
      this.oBaseGrid.toolbar.refresh.isDisable = true;
      this.oBaseGrid.toolbar.audit.isDisable = true;
    }
  }

  private setTempToolbarStatusUnDisabled(
    p: N_oSetupPanel.N_comps.T_eventCoordinationToolbar
  ) {
    if (this.toolbarStatusBak) {
      this.oBaseGrid.toolbar = this.toolbarStatusBak;
      this.toolbarStatusBak = null;
    }
  }

  // 处理组件协调
  public sendEventCoordination(
    type: N_oSetupPanel.N_comps.T_eventCoordinationToolbar
  ) {
    if (!this.oBaseGrid.isCoordination) {
      return;
    }
    const r = this.TCoordination.sendEventCoordination(
      type,
      this.oBaseGrid.$bus
    )
      .then(([b, msg]) => {})
      .catch(msg => {
        console.error(msg);
        // this.oBaseGrid.$msg(msg);
      });
  }

  // 从getfun api里新增加的属性，用此决定一个功能的i18n字段，字段的m2o的来源表描述字段是否是国际化字段
  public isI18nField(fieldName: string): boolean {
    const funI18nFields = this.oBaseGrid.funI18nFields;
    if (funI18nFields) {
      return funI18nFields.indexOf(fieldName) !== -1;
    }
    return false;
  }

  public setCustBtnStatusByRowChk() {
    const s: boolean = this.grid.getCheckboxRecords().length > 0;

    this.oBaseGrid._config.toolbar.addon.forEach(ele => {
      if (ele?.chkEnabled === true) {
        this.handleCustBtnStatus(ele.title, 'auth', s);
      }
      if (ele?.chkShow === true) {
        this.handleCustBtnStatus(ele.title, 'isShow', s);
      }
    });
  }

  public setCustBtnStatusByEditStatus(status: boolean) {
    this.oBaseGrid._config.toolbar.addon.forEach(ele => {
      if (ele?.editedEnabled === true) {
        this.handleCustBtnStatus(ele.title, 'auth', status);
      }
      if (ele?.editedShow === true) {
        this.handleCustBtnStatus(ele.title, 'isShow', status);
      }
    });
  }

  public handleCustBtnStatus(btnTitle: string, status: string, value: boolean) {
    const a = this.oBaseGrid.customPermission.data[btnTitle] ?? 1;
    if (a === 1) {
      this.oBaseGrid.toolbar['addon'].forEach(el => {
        if (el.title === btnTitle) {
          el[status] = value;
        }
      });
    }
  }

  /**
   * 处理标准按钮前后事件
   * @param actionName 按钮名
   * @param callback 按钮回调函数（注：必须是promise）
   */
  public handleBtnActions(
    actionName: string,
    callback: () => Promise<boolean>
  ) {
    const actions = this.getActionCfg();
    const name = actionName.replace(/^./, match => match.toUpperCase());

    if (actions[`before${name}`]) {
      const bParams = this.getSelectedData('select');
      bParams.title = actions[`before${name}`];
      bParams.from = `before${name}`;
      this.doEvent(actions[`before${name}`], bParams).then(_ => {
        if (_) {
          callback().then(res => {
            if (res && actions[`after${name}`]) {
              const aParams = this.getSelectedData('select');
              aParams.title = actions[`after${name}`];
              aParams.from = `after${name}`;
              this.doEvent(actions[`after${name}`], aParams);
            }
          });
        }
      });
    } else {
      callback().then(r => {
        if (r && actions[`after${name}`]) {
          const aParams = this.getSelectedData('select');
          aParams.title = actions[`after${name}`];
          aParams.from = `after${name}`;
          this.doEvent(actions[`after${name}`], aParams);
        }
      });
    }
  }

  /**
   * @description: 关于 审核/审批的按钮 状态
   * @param {string} property :按钮属性名 isDisable isShow auth value
   * @param {boolean} status :按钮属性值
   * @return {*}
   * @author: swc
   * @Date: 2024-09-23 16:46:05
   * @LastEditors: zss
   * @LastEditTime: Do not edit
   */
  public requestAuditBtnStatus(
    property: string = 'isDisable',
    status: boolean = true
  ) {
    const that = this.oBaseGrid;
    that.toolbar?.requestAudit &&
      (that.toolbar.requestAudit[property] = status);
    that.toolbar?.antiAudit && (that.toolbar.antiAudit[property] = status);
    that.toolbar?.auditStatus && (that.toolbar.auditStatus[property] = status);
    that.toolbar?.revokeApproval &&
      (that.toolbar.revokeApproval[property] = status);
    that.toolbar?.audit && (that.toolbar.audit[property] = status);
    that.toolbar?.unaudit && (that.toolbar.unaudit[property] = status);
    that.toolbar?.accountPosted &&
      (that.toolbar.accountPosted[property] = status);
    that.toolbar?.cancelPost && (that.toolbar.cancelPost[property] = status);
    that.toolbar?.caseclosed && (that.toolbar.caseclosed[property] = status);
    that.toolbar?.anticlosing && (that.toolbar.anticlosing[property] = status);
    that.toolbar?.freeze && (that.toolbar.freeze[property] = status);
    that.toolbar?.unfreeze && (that.toolbar.unfreeze[property] = status);
    that.toolbar?.void && (that.toolbar.void[property] = status);
  }
}
export interface I_editor extends T_editor {}
